/**
 * object数组 字段转换
 * @param arr {Array<Object>}
 * @param convertFields {{ field: string }}
 * @returns {{}[]}
 */
import YouXin from 'youxin-js-sdk';

export function objectListFieldConvert (arr = [], convertFields = {}) {
  return arr.map(item => {
    return Object.keys(convertFields).reduce((result, field) => {
      if (field && item && item[field]) {
        const convertedField = convertFields[field];
        result[convertedField] = item[field];
      }

      return result;
    }, {});
  });
}

/**
 * 获取最后一个元素
 * @param arr
 * @returns {*}
 */
export function last (arr = []) {
  return arr[arr.length - 1];
}

/**
 * 获取第一个元素
 * @param arr
 * @returns {*}
 */
export function first (arr = []) {
  return arr[0];
}

/**
 * 字段抽取 sampling([{a: 1}], 'a') === [1]
 * @param arr
 * @param field { String }
 * @returns {*[]}
 */
export function sampling (arr = [], field = '') {
  return arr.filter(item => item).map(item => item[field]);
}

/**
 * 去重
 * @param arr
 * @param field
 * @returns {unknown[]}
 */
export function distinctObjectList (arr = [], field = 'id') {
  return [...new Set(sampling(arr, field))].map(val =>
    arr.find(item => item[field] === val)
  );
}

/**
 * 合并 Object[]
 * @param arr Array<Object>>
 * @param obj {Object}
 * @returns {*}
 */
export function mergeObjectArr (arr, objOrFunc = {}) {
  return arr
    .filter(item => item)
    .map(item => ({
      ...item,
      ...(typeof objOrFunc === 'function' ? objOrFunc(item) : objOrFunc || {})
    }));
}

/**
 * @description: 产品模块数组转为树
 * @param {type}
 * @return:
 */

export function modsConvertTree (arr = []) {
  const moduleId = [];
  arr.forEach(item => {
    moduleId.push(item.moduleId);
  });
  const treeArr = [];
  arr.forEach(item => {
    if (!item.parentId || !moduleId.includes(item.parentId)) {
      treeArr.push(getChildrenByParentId(arr, item.moduleId, item));
    }
  });
  return treeArr;
}

export function getChildrenByParentId (arr = [], parentId = null, obj = {}) {
  const children = [];
  arr.forEach(item => {
    if (item.parentId === parentId) {
      children.push(item);
      getChildrenByParentId(arr, item.moduleId, item);
    }
  });
  obj.children = children;
  return obj;
}
/**
 * @description 深拷贝
 * @param {*} obj: Array | Object
 */
export const clone = function (obj) {
  const objClone = Array.isArray(obj) ? [] : {};
  if (obj && typeof obj === 'object') {
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        if (obj[key] && typeof obj[key] === 'object') {
          objClone[key] = clone(obj[key]);
        } else {
          objClone[key] = obj[key];
        }
      }
    }
  }
  return objClone;
};

/**
 * iframe 高度
 */
// export const setIframeHeight = function (num) {
//   const HOSTNAME = window.location.host;
//   if (typeof (window.postMessage) !== undefined) {
//     parent.postMessage({ type: 'mainFrameHeight', value: num }, `${HOSTNAME}`);
//   }
// };
/**
 * 换算单位成 B K MK G
 */
export const computedSize = function (size) {
  if (!size) return '0B';
  const num = 1024.0;
  if (size < num) return size + 'B';
  if (size < Math.pow(num, 2)) return (size / num).toFixed(2) + 'KB';
  if (size < Math.pow(num, 3)) {
    return (size / Math.pow(num, 2)).toFixed(2) + 'M';
  }
  if (size < Math.pow(num, 4)) {
    return (size / Math.pow(num, 3)).toFixed(2) + 'G';
  }
  return (size / Math.pow(num, 4)).toFixed(2) + 'T';
};
/**
 * @description 换算单位为 G
 * @param {*} size：String
 */
export const computedG = function (size) {
  if (!size) return '0';
  const num = 1024.0;
  return (size / Math.pow(num, 3)).toFixed(2);
};

/**
 * @Desc 上传图片 参数处理
 */
export const deleteFileFix = function (ary) {
  ary.forEach(item => {
    if (item.code === '200') {
      const _data = item.data || {},
        fileName = _data.fileName || '';
      _data.fileName =
        fileName && fileName.substring(0, fileName.lastIndexOf('.'));
      _data.fileType =
        fileName &&
        fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length);
    }
  });
  return ary;
};

/**
 * 上传图片
 */
export function uploadImg (num = 1, nameStr = ['album', 'camera']) {
  return new Promise((resolve, reject) => {
    YouXin.chooseImage({
      count: num, // 默认为1张，暂时只支持1张
      sourceType: nameStr,
      isCrop: '0',
      success (src) {
        YouXin.uploadFile({
          localId: src,
          isShowProgressTips: 0,
          success (result) {
            const objName = result.map(item => item.result),
              ary = deleteFileFix(objName);
            resolve(ary);
          },
          error (err) {
            reject(new Error(err));
          }
        });
      }
    });
  });
}

// 数字进制转换，num:需要转换的参数，point：保留小数点后几位
export const tranNumber = function (num, point) {
  const numStr = num.toString();
  // 十万以内直接返回
  if (numStr.length < 6) {
    return numStr;
  } else if (numStr.length > 8) {
    // 大于8位数是亿
    const decimal = numStr.substring(
      numStr.length - 8,
      numStr.length - 8 + point
    );
    return parseFloat(parseInt(num / 100000000) + '.' + decimal) + '亿';
  } else if (numStr.length > 5) {
    // 大于6位数是十万 (以10W分割 10W以下全部显示)
    const decimal = numStr.substring(
      numStr.length - 4,
      numStr.length - 4 + point
    );
    return parseFloat(parseInt(num / 10000) + '.' + decimal) + '万';
  }
};

export function getAreaIdList (str = '') {
  const arr = str.split('.');

  return Array.from({ length: arr.length }, (v, i) => {
    return arr.slice(0, i + 1).join('.');
  });
}

/**
 * @module
 * @description 获取url参数
 */
export const getUrlArgs = function () {
  const argStr = window.location.search
      ? window.location.search.substring(1)
      : '',
    argObj = {},
    argArr = argStr.length > 0 ? argStr.split('&') : [];
  let item = null,
    value = null,
    key = null;
  for (var i = 0, len = argArr.length; i < len; i++) {
    item = argArr[i].split('=');
    key = decodeURIComponent(item[0]);
    value = decodeURIComponent(item[1]);
    argObj[key] = value;
  }
  return argObj;
};

/**
 * 判断资源是否在授课包里
 * packList：授课包列表id
 * row：Object 如果id+1 或者id+3和 列表对比, 好友推荐资源判断取itemId
 */
export const checkIsPack = function (packList = [], row = {}) {
  const newAry = [];
  packList.forEach(item => {
    const bagId = item.code + item.type;
    if (!newAry.includes(bagId)) {
      newAry.push(bagId);
    }
  });
  if (
    newAry.includes(row.id + '1') ||
    newAry.includes(row.id + '3') ||
    newAry.includes(row.itemId + '1') ||
    newAry.includes(row.itemId + '3')
  ) {
    return true;
  } else {
    return false;
  }
};

export const mineType = function (params) {
  const mimeTypeMap = new Map();
  // mimeTypeMap.set(后缀名，MIME类型}
  mimeTypeMap.set('.3gp', 'video/3gpp');
  mimeTypeMap.set('.apk', 'application/vnd.android.package-archive');
  mimeTypeMap.set('.asf', 'video/x-ms-asf');
  mimeTypeMap.set('.avi', 'video/x-msvideo');
  mimeTypeMap.set('.bin', 'application/octet-stream');
  mimeTypeMap.set('.bmp', 'image/bmp');
  mimeTypeMap.set('.c', 'text/plain');
  mimeTypeMap.set('.class', 'application/octet-stream');
  mimeTypeMap.set('.conf', 'text/plain');
  mimeTypeMap.set('.cpp', 'text/plain');
  mimeTypeMap.set('.doc', 'application/msword');
  mimeTypeMap.set('.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
  mimeTypeMap.set('.xls', 'application/vnd.ms-excel');
  mimeTypeMap.set('.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  mimeTypeMap.set('.exe', 'application/octet-stream');
  mimeTypeMap.set('.gif', 'image/gif');
  mimeTypeMap.set('.gtar', 'application/x-gtar');
  mimeTypeMap.set('.gz', 'application/x-gzip');
  mimeTypeMap.set('.h', 'text/plain');
  mimeTypeMap.set('.htm', 'text/html');
  mimeTypeMap.set('.html', 'text/html');
  mimeTypeMap.set('.jar', 'application/java-archive');
  mimeTypeMap.set('.java', 'text/plain');
  mimeTypeMap.set('.jpeg', 'image/jpeg');
  mimeTypeMap.set('.jpg', 'image/jpeg');
  mimeTypeMap.set('.js', 'application/x-javascript');
  mimeTypeMap.set('.log', 'text/plain');
  mimeTypeMap.set('.m3u', 'audio/x-mpegurl');
  mimeTypeMap.set('.m4a', 'audio/mp4a-latm');
  mimeTypeMap.set('.m4b', 'audio/mp4a-latm');
  mimeTypeMap.set('.m4p', 'audio/mp4a-latm');
  mimeTypeMap.set('.m4u', 'video/vnd.mpegurl');
  mimeTypeMap.set('.m4v', 'video/x-m4v');
  mimeTypeMap.set('.mov', 'video/quicktime');
  mimeTypeMap.set('.mp2', 'audio/x-mpeg');
  mimeTypeMap.set('.mp3', 'audio/x-mpeg');
  mimeTypeMap.set('.mp4', 'video/mp4');
  mimeTypeMap.set('.mpc', 'application/vnd.mpohun.certificate');
  mimeTypeMap.set('.mpe', 'video/mpeg');
  mimeTypeMap.set('.mpeg', 'video/mpeg');
  mimeTypeMap.set('.mpg', 'video/mpeg');
  mimeTypeMap.set('.mpg4', 'video/mp4');
  mimeTypeMap.set('.mpga', 'audio/mpeg');
  mimeTypeMap.set('.msg', 'application/vnd.ms-outlook');
  mimeTypeMap.set('.ogg', 'audio/ogg');
  mimeTypeMap.set('.pdf', 'application/pdf');
  mimeTypeMap.set('.png', 'image/png');
  mimeTypeMap.set('.pps', 'application/vnd.ms-powerpoint');
  mimeTypeMap.set('.ppt', 'application/vnd.ms-powerpoint');
  mimeTypeMap.set('.pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation');
  mimeTypeMap.set('.prop', 'text/plain');
  mimeTypeMap.set('.rc', 'text/plain');
  mimeTypeMap.set('.rmvb', 'audio/x-pn-realaudio');
  mimeTypeMap.set('.rtf', 'application/rtf');
  mimeTypeMap.set('.sh', 'text/plain');
  mimeTypeMap.set('.tar', 'application/x-tar');
  mimeTypeMap.set('.tgz', 'application/x-compressed');
  mimeTypeMap.set('.txt', 'text/plain');
  mimeTypeMap.set('.wav', 'audio/x-wav');
  mimeTypeMap.set('.wma', 'audio/x-ms-wma');
  mimeTypeMap.set('.wmv', 'audio/x-ms-wmv');
  mimeTypeMap.set('.wps', 'application/vnd.ms-works');
  mimeTypeMap.set('.xml', 'text/plain');
  mimeTypeMap.set('.z', 'application/x-compress');
  mimeTypeMap.set('.zip', 'application/x-zip-compressed');
  mimeTypeMap.set('', '*/*');
  console.log(mimeTypeMap.get('.mp3'));
  return (mimeTypeMap.get(params));
};
